<?php

class ome_mdl_branch extends dbeav_model{
    public function _filter($filter,$tableAlias=null,$baseWhere=null){
		$op_id = kernel::single('desktop_user')->get_id();
		if($op_id){//如果是系统同步，是没有当前管理员，默认拥有所有仓库权限
		    $is_super = kernel::single('desktop_user')->is_super();
			if (!$is_super){
				$branch_ids = $this->getBranchByUser(true);
				if ($branch_ids){
                   if($filter['branch_id'] && in_array($filter['branch_id'], $branch_ids)){
                        $filter['branch_id'] = $filter['branch_id'];
                    }else{
                        $filter['branch_id'] = $branch_ids;
                    }
				}else{
					$filter['branch_id'] = 'false';
				}
			}
		}
        return parent::_filter($filter,$tableAlias,$baseWhere).$where;
    }

    /*
     * 获取仓库对应的快递公司列表
     *
     * @param int $branch_id
     *
     * @return array
     */
    function get_corp($branch_id){
        if(!$this->db->selectrow("SELECT region_id FROM sdb_ome_branch_area WHERE branch_id=".intval($branch_id))){
            return $this->db->select("SELECT corp_id,name FROM sdb_ome_dly_corp WHERE disabled='false' ORDER BY weight DESC");   //代表该仓库找不到地区，默认为任意地方，所以任意物流公司都可送
        }else{
            //获取没有设置地区的物流公司，代表这类物流公司哪都送
            $corp1 = $this->db->select("SELECT corp_id,name FROM sdb_ome_dly_corp WHERE disabled='false' AND corp_id NOT IN(SELECT DISTINCT(corp_id) FROM sdb_ome_dly_corp_area) ORDER BY weight DESC");
            //获取物流公司和仓库有地区交叉的物流公司
            $oRegion = &app::get('ectools')->model('regions');
            $rows = $this->db->select("SELECT corp_id,region_id FROM sdb_ome_dly_corp_area");
            $region_ids = array();
            foreach($rows as $v){
                $region_ids[$v['corp_id']][] = $v['region_id'];
                $region = $oRegion->dump($v['region_id'],"local_name,region_path");

                $region_path = explode(",",$region['region_path']);
                array_shift($region_path);
                array_pop($region_path);
                array_pop($region_path);

                if($region_path){
                    foreach($region_path as $id){
                        if(!in_array($id,$region_ids[$v['corp_id']])){
                            $region_ids[$v['corp_id']][] = $id;
                        }
                    }
                }
            }

            $branch_region = $this->db->select("SELECT region_id FROM sdb_ome_branch_area WHERE branch_id=".$branch_id);
            $corp_region = array();
            foreach($branch_region as $v){
                $corp_region[] = $v['region_id'];
                $region = $oRegion->dump($v['region_id'],"local_name,region_path");

                $region_path = explode(",",$region['region_path']);
                array_shift($region_path);
                array_pop($region_path);
                array_pop($region_path);

                if($region_path){
                    foreach($region_path as $id){
                        if(!in_array($id,$corp_region)){
                            $corp_region[] = $id;
                        }
                    }
                }
            }

            $corp_list = array();
            foreach($region_ids as $k=>$v){
                if(array_intersect($v,$corp_region)){
                    $corp_list[] = $k;
                }
            }


            if(empty($corp_list)){
                return $corp1;
            }else{
                $corp2 = $this->db->select("SELECT corp_id,name FROM sdb_ome_dly_corp WHERE disabled='false' AND corp_id IN(".implode(",",$corp_list).") ORDER BY weight DESC");
                return array_merge($corp1,$corp2);
            }
        }

    }

    function save_branch($data){
        $oBranch_area = &$this->app->model("branch_area");
        $areaGroupId = $data['areaGroupId'];
        $tmpGroupId = $oBranch_area->Getregion_id($areaGroupId);
        if($data['branch_id']!=''){
            $ret_region=$oBranch_area->Get_region($data['branch_id']);
            foreach($ret_region as $k=>$v){
                if(in_array($v,$tmpGroupId)==false){
                    $oBranch_area->Del_area($data['branch_id'],$v);
                }
            }
        }
        $this->save($data);
        foreach($tmpGroupId as $k=>$v){
            $tmpdata=array(
                'branch_id'=>$data['branch_id'],
                'region_id'=>$v
            );
            $oBranch_area->save($tmpdata);
        }
    }

    function Get_name($branch_id){
        $branch = $this->dump($branch_id,'name');
        return $branch['name'];
    }
     /*获取仓库列表*/
    function Get_branchlist(){
        $branch = $this->getList('branch_id,name','',0,-1);

        return $branch;
    }
  /*
   * 获取仓库对应货号列表
   */
    function Get_poslist($branch_id){

       $pos = $this->db->select('SELECT pos_id,store_position FROM sdb_ome_branch_pos WHERE branch_id='.$branch_id);


       return $pos;
    }

    function fgetlist_csv(&$data,$filter,$offset){
        $limit = 100;
        if( $filter['_gType'] ){
            $title = array();
            if(!$data['title'])$data['title'] = array();
            $data['title'][''.$filter['_gType']] = '"'.implode('","',$this->io->data2local($this->io_title(array('type_id'=>$filter['_gType']))) ).'"';
         }
         return false;
    }

     function io_title( $filter,$ioType='csv' ){
        $title = array();

        switch( $ioType ){
            case 'csv':
            default:

                $title = array(
                    $filter['type_id'],
                    'bn',
                    'name',
                    'store',
                    'sku_property',
                    'weight',
                    'store_position',

                );

                break;
        }
        $this->ioTitle['csv'][$filter['type_id']] = $title;
        return $title;
    }

    function export_csv($data){
        $output = array();
        foreach( $data['title'] as $k => $val ){
            $output[] = $val."\n".implode("\n",(array)$data['content'][$k]);
        }
        echo implode("\n",$output);
    }

    /*
     * 获取操作员管辖仓库
     * getBranchByUser
     */
    function getBranchByUser($dataType=null){
        $oBops =  &$this->app->model('branch_ops');
        $Obranch = &$this->app->model('branch');

        $opInfo = kernel::single('ome_func')->getDesktopUser();
        $op_id = $opInfo['op_id'];

        $bops_list = $oBops->getList('branch_id', array('op_id'=>$op_id), 0, -1);
        if ($bops_list)
        foreach ($bops_list as $k=>$v){
            $bps[] = $v['branch_id'];
        }
        if ($dataType) return $bps;
        if ($bps)
        $branch_list = $Obranch->getList('branch_id,name,uname,phone,mobile', array('branch_id'=>$bps), 0, -1);
        if ($branch_list) ksort($branch_list);
        return $branch_list;
    }

   /*
     * 删除仓库：
     * 拒绝删除条件：关联货位
     */
    function pre_recycle($data=null){
       $Obranch_product = &$this->app->model('branch_product');
       $Obranch_pos = &$this->app->model('branch_pos');
       $Obranch = &$this->app->model('branch');
       if(is_array($_POST['branch_id'])){
            foreach ($_POST['branch_id'] as $key=>$val){
                #仓库与货位关联
                $Obranch_detail = $Obranch->dump($val, 'name');
                $pos = $Obranch_pos->dump(array('branch_id'=>$val),'pos_id');
                if(!empty($pos)){
                    echo '仓库：'.$Obranch_detail['name'].'已与货位建立关系,无法删除!';
                    return false;
                }
                #仓库与商品关联
                $Obranch_product_detail = $Obranch_product->dump(array('branch_id'=>$val), 'product_id');
                if(!empty($Obranch_product_detail)){
                    echo '仓库：'.$Obranch_detail['name'].'已与商品建立关系,无法删除!';
                    return false;
                }
                $deled .= $Obranch_detail['name']." - ";
            }
            echo '仓库:'. $deled. '已成功删除！';
            return true;
       }
    }

    function isExistOfflineBranch(){
    	$row = $this->db->selectRow('select count(*) as total from  sdb_ome_branch where attr="false"');
    	if($row['total'] > 0){
    		return true;
    	}else{
    		return false;
    	}
    }

 	function isExistOnlineBranch(){
    	$row = $this->db->selectRow('select count(*) as total from  sdb_ome_branch where attr="true"');
    	if($row['total'] > 0){
    		return true;
    	}else{
    		return false;
    	}
    }

	function getOnlineBranchs($field='*'){
    	$rows = $this->db->select('select '.$field.' from sdb_ome_branch where attr="true" order by weight desc');

    	return $rows;
    }

	function getOfflineBranchs($field='*'){
    	$rows = $this->db->select('select '.$field.' from sdb_ome_branch where attr="false" order by weight desc');

    	return $rows;
    }

	function getAllBranchs($field='*'){
    	$rows = $this->db->select('select '.$field.' from sdb_ome_branch order by weight desc');

    	return $rows;
    }
}
?>